import React, {useEffect, useMemo, useState} from "react";
import {Input, PageContainer, Picker, View, Text} from "@tarojs/components"
import account from "@/store/account";
import PageBottom from "@/components/pageBottom";
import CategorySelecter from "@/components/categorySelecter";
import {categoryType} from "@/types";
import {VibrateShort} from "@/utils";
import moment from "moment";

import "./index.scss"

interface filterType {
    startDate?: string,
    endDate?: string,
    note?: string,
    type?: number,
    userId?: number,
    userName?: string,
    categoryId?: number,
    categoryName?: string
}

const BillFilter: React.FC<{
    show: boolean,
    data: filterType,
    onConfirm: (val: filterType) => void,
    onClose: () => void,
    onCancel?: () => void
}> = ({
          show,
          data,
          onClose,
          onConfirm,
          onCancel,
      }) => {
    const [isVisible, setIsVisible] = useState(false)
    const [categoryVisible, setCategoryVisible] = useState(false)
    const [filterData, setFilterData] = useState<filterType>({})

    useEffect(() => {
        if (show) {
            setIsVisible(true)
        } else {
            setTimeout(() => {
                setIsVisible(false)
            }, 200)
        }
    }, [show])

    useEffect(() => {
        setFilterData({...data})
    }, [show])

    const userIndex = useMemo(() => {
        const list = account.activeAccount?.members || []
        return filterData.userId ? list.findIndex(item => {
            item.userId === filterData.userId
        }) : 0
    }, [account.activeAccount])

    const memberChange = (index: number | string) => {
        const member = (account.activeAccount?.members || [])[index]
        filterChange(member, 'member')
    }

    const filterChange = (value: any, key?: string) => {
        if (typeof value !== 'object' && key) {
            setFilterData({
                ...filterData,
                [key]: value
            })
        } else {
            setFilterData({
                ...filterData,
                ...value
            })
        }
    }

    const openCategory = () => {
        setIsVisible(false)
        setTimeout(() => {
            setCategoryVisible(true)
        }, 0)
    }

    const categorySelectFinish = (category?: categoryType) => {
        const categoryId = category?.id
        const categoryName = category?.name
        if (categoryId && categoryName) {
            setFilterData({
                ...filterData,
                categoryId,
                categoryName
            })
        }
        setCategoryVisible(false)
        setTimeout(() => {
            setIsVisible(true)
        }, 250)
    }

    return (
        <View>
            {
                isVisible ? <PageContainer show={show} onLeave={onClose} overlay round zIndex={9999}>
                    <View className="bill-filter-container card-background flex-column flex-item">
                        <View className="title-container flex-row flex-item">
                            <View className="filter-title flex1 font-size36">请选择筛选条件</View>
                            <View className="clear-btn font-size24" onClick={() => setFilterData({
                                startDate: moment().startOf('month').format('YYYY-MM-DD'),
                                endDate: moment().format('YYYY-MM-DD')
                            })}>重置筛选</View>
                        </View>
                        <View className="bill-filter-body">
                            <View className="bill-filter-item flex-row flex-item">
                                <View className="bill-filter-item-label flex-column flex-center">
                                    <View className="iconfont icon-fin-salem font-size24"></View>
                                    <View className="font-size20">收支</View>
                                </View>
                                <View className="flex1 flex-column">
                                    <View className="flex-row flex-item flex1">
                                        <Picker mode="selector"
                                                className="flex1"
                                                range={['支出', '收入']}
                                                value={filterData.type || 0}
                                                onChange={e => filterChange(Number(e.detail.value), 'type')}>
                                            <View className="bill-filter-item-val font-size28 flex1">
                                                {
                                                    filterData.type === undefined ?
                                                        <View className="grey-color-text">请选择</View>:
                                                        <View>{['支出', '收入'][filterData.type]}</View>
                                                }
                                            </View>

                                        </Picker>
                                        {
                                            filterData.type !== undefined ?
                                                <Text onClick={() => filterChange(undefined, 'type')} className="iconfont icon-base-close2 font-size36"></Text> :
                                                null
                                        }
                                    </View>
                                    <View className="bottom-line"></View>
                                </View>
                            </View>
                            <View className="bill-filter-item flex-row flex-item">
                                <View className="bill-filter-item-label flex-column flex-center">
                                    <View className="iconfont icon-riqi font-size24"></View>
                                    <View className="font-size20">日期</View>
                                </View>
                                <View className="flex1 flex-column">
                                    <View className="flex-row flex-item">
                                        <Picker mode="date"
                                                fields="day"
                                                className="flex1"
                                                value={filterData.startDate || ''}
                                                end={filterData.endDate}
                                                onChange={e => filterChange(e.detail.value, 'startDate')}>
                                            <View
                                                className={`bill-filter-item-val text-center font-size28 flex1 ${filterData.startDate ? '' : 'grey-color-text'}`}>
                                                {filterData.startDate || '请选择'}
                                            </View>
                                        </Picker>
                                        <Text>至</Text>
                                        <Picker mode="date"
                                                fields="day"
                                                className="flex1"
                                                value={filterData.endDate || ''}
                                                start={filterData.startDate}
                                                onChange={e => filterChange(e.detail.value, 'endDate')}>
                                            <View
                                                className={`bill-filter-item-val text-center font-size28 flex1 ${filterData.endDate ? '' : 'grey-color-text'}`}>
                                                {filterData.endDate || '请选择'}
                                            </View>
                                        </Picker>
                                    </View>
                                    <View className="bottom-line"></View>
                                </View>
                            </View>
                            <View className="bill-filter-item flex-row flex-item">
                                <View className="bill-filter-item-label flex-column flex-center">
                                    <View className="iconfont icon-leibiefenlei font-size24"></View>
                                    <View className="font-size20">分类</View>
                                </View>
                                <View className="flex1 flex-column">
                                    <View className="flex-row flex-item font-size28 flex1">
                                        <View
                                            onClick={openCategory}
                                            className={`bill-filter-item-val flex1 ${filterData.categoryName ? '' : 'grey-color-text'}`}>
                                            {filterData.categoryName || '请选择'}
                                        </View>
                                        {
                                            filterData.categoryName ?
                                                <Text onClick={() => setFilterData({
                                                    ...filterData,
                                                    categoryId: undefined,
                                                    categoryName: undefined
                                                })} className="iconfont icon-base-close2 font-size36"></Text> :
                                                null
                                        }
                                    </View>
                                    <View className="bottom-line"></View>
                                </View>
                            </View>
                            <View className="bill-filter-item flex-row flex-item">
                                <View className="bill-filter-item-label flex-column flex-center">
                                    <View className="iconfont icon-bijijilu font-size24"></View>
                                    <View className="font-size20">备注</View>
                                </View>
                                <View className="flex1 flex-column">
                                    <View className="flex-row flex-item flex1">
                                        <Input className="bill-filter-item-val font-size28 flex1"
                                            value={filterData.note}
                                            onInput={e => filterChange(e.detail.value, 'note')}
                                            placeholder="请输入"></Input>
                                        {
                                            filterData.note ?
                                                <Text onClick={() => filterChange('', 'note')} className="iconfont icon-base-close2 font-size36"></Text> :
                                                null
                                        }
                                    </View>
                                    <View className="bottom-line"></View>
                                </View>
                            </View>
                            <View className="bill-filter-item flex-row flex-item">
                                <View className="bill-filter-item-label flex-column flex-center">
                                    <View className="iconfont icon-user-name font-size24"></View>
                                    <View className="font-size20">成员</View>
                                </View>
                                <View className="flex1 flex-column">
                                    <View className="flex-row flex-item flex1">
                                        <Picker mode="selector"
                                                className="flex1"
                                                range={account.activeAccount?.members || []}
                                                rangeKey="userName"
                                                value={userIndex}
                                                onChange={e => memberChange(e.detail.value)}>
                                            <View
                                                className={`bill-filter-item-val font-size28 flex1 ${filterData.userName ? '' : 'grey-color-text'}`}>
                                                {filterData.userName || '请选择'}
                                            </View>
                                        </Picker>
                                        {
                                            filterData.userId !== undefined ?
                                                <Text onClick={() => setFilterData({
                                                    ...filterData,
                                                    userName: undefined,
                                                    userId: undefined
                                                })} className="iconfont icon-base-close2 font-size36"></Text> :
                                                null
                                        }
                                    </View>
                                    <View className="bottom-line"></View>
                                </View>
                            </View>
                        </View>
                        <PageBottom onConfirm={() => {
                            VibrateShort()
                            onConfirm(filterData)
                        }} onCancel={() => {
                            VibrateShort()
                            onCancel ? onCancel() : onClose()
                        }}></PageBottom>
                    </View>
                </PageContainer> : null
            }
            <CategorySelecter
                show={categoryVisible}
                value={filterData.categoryId}
                onClose={categorySelectFinish}
                onSure={categorySelectFinish}>
            </CategorySelecter>
        </View>
    )
}
export default BillFilter